####-------------------------------------------------------------------------------------####
# SSQ: Weber, Davis, Klar
# Primary Analysis File

####-------------------------------------------------------------------------------------####
rm(list=ls())
require(foreign)
require(car)
require(pscl)
require(multinomRob)
require(corrplot)
####-------------------------------------------------------------------------------------####
###  Load Data ##
source("/Users/chrisweber/Dropbox/Working Projects/Nick Davis_Polarization Emotion/analysis/paper functions_FINAL.R")
load("/Users/chrisweber/Dropbox/Working Projects/Nick Davis_Polarization Emotion/data/data.full.FINAL.Rdata")
#load("/Users/chrisweber/Dropbox/Working Projects/Nick Davis_Polarization Emotion/data/data.polarize.Rdata")
d1<-data
cor.test(d1$policy.conservatism, d1$ideology3) # 0.47


### Start with MPLUS Models
#   Note: These two datasets must be  run in MPLUS and then the outfile imported here.
#  
# d1$pid.number<-recode(d1$pid.3, "'Republican'=1; 'Democrat'=2; 'Independent'=3")
# write.csv(with(d1, cbind(anger.in, anger.out, dem.anger*4+1, rep.anger*4+1, fear.in, fear.out,
#                           dem.fear*4+1, rep.fear*4+1, hope.in, hope.out, dem.hope*4+1, rep.hope*4+1,
#                           pride.in, pride.out, dem.pride*4+1, rep.pride*4+1, pid.number,feeling.repc, feeling.demc, feeling.dems, feeling.reps)), 
#           file="/users/chrisweber/Dropbox/Working Projects/Nick Davis_Polarization Emotion/data/mplus1_FINAL.csv")
# 
# 
#    
# no.ind<-subset(d1, pid.number!=3 )
#  write.csv(with(no.ind, cbind(anger.in*4+1, anger.out*4+1, dem.anger*4+1, rep.anger*4+1, fear.in*4+1, fear.out*4+1,
#                           dem.fear*4+1, rep.fear*4+1, hope.in*4+1, hope.out*4+1, dem.hope*4+1, rep.hope*4+1,
#                           pride.in*4+1, pride.out*4+1, dem.pride*4+1, rep.pride*4+1, pid.number, feeling.repc, feeling.demc, feeling.dems, feeling.reps)), 
#            file="/users/chrisweber/Dropbox/Working Projects/Nick Davis_Polarization Emotion/data/mplus2_FINAL.csv")


require(MplusAutomation)
outfile="/Users/chrisweber/Dropbox/Working Projects/Nick Davis_Polarization Emotion/analysis/MPLUS1_CFA_FINAL.out"

pdf("/Users/chrisweber/Dropbox/Working Projects/Nick Davis_Polarization Emotion/Paper/Figure1.pdf", width=8, height=5)
 semPlot::semPaths(outfile, what="paths", "est", style="lisrel", rotation=1,
                   thresholds=FALSE, residuals=FALSE, intercepts=FALSE, 
                   sizeMan2=3, sizeMan=9, sizeLat2=8, sizeLat=13, 
                   label.prop=0.5, label.cex=0.6, title=TRUE, node.width=1,
                   edge.label.cex = 0.70, 
                   nCharNodes=0, label.font=4, label.scale=FALSE, curve=2)
dev.off()                  

##Racial Resentment
d1$racial.resentment<-(rowMeans(cbind(d1$rr1, d1$rr2, d1$rr3, d1$rr4), na.rm=T)-1)/4
d1$anxiety.out<-rowMeans(cbind(d1$anger.out, d1$fear.out), na.rm=T) 
d1$enthusiasm.in<-rowMeans(cbind(d1$hope.in, d1$pride.in), na.rm=T)
d1$anxiety.in<-rowMeans(cbind(d1$anger.in, d1$fear.in), na.rm=T) 
d1$enthusiasm.out<-rowMeans(cbind(d1$hope.out, d1$pride.out), na.rm=T)

d1$ideology.7<-d1$ideology3*6+1

d1$ideo.group<-NA
d1$ideo.group<-ifelse(d1$policy.conservatism<quantile(d1$policy.conservatism, 0.25), 1, ifelse(d1$policy.conservatism>quantile(d1$policy.conservatism, 0.75), 3,2))

### Does promote the alignment between symbolic and operational ideology
d1$id.3cat<-recode(d1$ideology3*6, "0:1='Liberal'; 2:4='Moderate'; 5:6='Conservative'")
table(d1$id.3cat)

####################################################################################
####################################################################################
####################################################################################
d1$intAnxIn<-d1$ideology3*d1$anxiety.in
d1$intAnxOut<-d1$ideology3*d1$anxiety.out
d1$intEnthIn<-d1$ideology3*d1$enthusiasm.in
d1$intEnthOut<-d1$ideology3*d1$enthusiasm.out

d1$year2008<-recode(d1$year, "2008=1; else=0")
d1$year2012<-recode(d1$year, "2012=1; else=0")
d1$year2016<-recode(d1$year, "2016=1; else=0")

d1$liberal.s<-ifelse(d1$id.3cat=="Liberal", 1, 0)
d1$conservative.s<-ifelse(d1$id.3cat=="Conservative", 1, 0)
d1$moderate.s<-ifelse(d1$id.3cat=="Moderate", 1, 0)

d1$intAnxIn1<-d1$liberal.s*d1$anxiety.in
d1$intAnxOut1<-d1$liberal.s*d1$anxiety.out
d1$intEnthIn1<-d1$liberal.s*d1$enthusiasm.in
d1$intEnthOu1t<-d1$liberal.s*d1$enthusiasm.out

d1$intAnxIn2<-d1$conservative.s*d1$anxiety.in
d1$intAnxOut2<-d1$conservative.s*d1$anxiety.out
d1$intEnthIn2<-d1$conservative.s*d1$enthusiasm.in
d1$intEnthOut2<-d1$conservative.s*d1$enthusiasm.out

m1a<-polr(as.factor(pid)~
            ideology3+anxiety.in+anxiety.out+enthusiasm.in+enthusiasm.out+
            intAnxIn+
            catholic+no.religion+other.religion+racial.resentment+
            female+education+news+non.white+
            age+year2012+year2016, data=d1)  
m1b<-polr(as.factor(pid)~
            ideology3+anxiety.in+anxiety.out+enthusiasm.in+enthusiasm.out+
            intAnxOut+
            catholic+no.religion+other.religion+racial.resentment+
            female+education+news+non.white+
            age+year2012+year2016, data=d1)  
m1c<-polr(as.factor(pid)~
            ideology3+anxiety.in+anxiety.out+enthusiasm.in+enthusiasm.out+
            intEnthIn+
            catholic+no.religion+other.religion+racial.resentment+
            female+education+news+non.white+
            age+year2012+year2016, data=d1)  
m1d<-polr(as.factor(pid)~
            ideology3+anxiety.in+anxiety.out+enthusiasm.in+enthusiasm.out+
            intEnthOut+
            catholic+no.religion+other.religion+racial.resentment+
            female+education+news+non.white+
            age+year2012+year2016, data=d1)  
m2<-polr(as.factor(pid)~
           ideology3+anxiety.in+anxiety.out+enthusiasm.in+enthusiasm.out+intAnxIn+
           intAnxOut+intEnthIn+intEnthOut+
           catholic+no.religion+other.religion+racial.resentment+
           female+education+news+non.white+
           age+year2012+year2016, data=d1)  



# PID/ Table 1/ Figure 2
## Table ###
out1<-rbind(coef(summary(m1a)) [c(1:6),1:2], c(NA,NA), c(NA,NA), c(NA,NA)) #ANES
out2<-rbind(coef(summary(m1b)) [c(1:5),1:2], c(NA,NA), coef(summary(m1b)) [c(6),1:2], c(NA,NA), c(NA,NA)) #ANES
out3<-rbind(coef(summary(m1c)) [c(1:5),1:2], c(NA,NA), c(NA,NA), coef(summary(m1c)) [c(6),1:2], c(NA,NA)) #ANES
out4<-rbind(coef(summary(m1d)) [c(1:5),1:2], c(NA,NA), c(NA,NA), c(NA,NA), coef(summary(m1d)) [c(6),1:2]) #ANES
out5<-rbind(coef(summary(m2)) [c(1:9),1:2]) #ANES


results1<-as.matrix(
  cbind(out1, out2, out3, out4, out5
  ))

row.names(results1)<-c("Ideology", "In Party Negative Affect", "Out Party Negative Affect", "In Party Positive Affect", "Out Party Positive Affect", "In Party Negative x Ideology", "Out Party Negative x Ideology", "In Party Positive x Ideology", "Out Party Positive x Ideology")
require(xtable)                  
xtable(results1, digits=3,
       caption="Partisan-Ideological Sorting by Emotion. Ordinal logistic regression estimates. Entries are point estimates and standard errors. 
       Entries in bold indicate a slope that is two times the estimated standard error.
       All models control for religion, racial resentment, gender, education, cross section, news consumption, race and age. The full models
       may be found in the appendix.")


xtable(summary(m2)$coefficients, digits=3,
       caption="Partisan-Ideological Sorting by Emotion. Ordinal logistic regression estimates. Entries are point estimates and standard errors. 
       Entries in bold indicate a slope that is two times the estimated standard error.
       All models control for religion, racial resentment, gender, education, cross section, news consumption, race and age. The full models
       may be found in the appendix.")

#########################################################################################################
#########################################################################################################
##################### Figure 2 ###############################################################
#########################################################################################################
## Functions to plot data ##
## Figure plots three plots -- marginal effects for ideology across four groups x pid

# pred.generator is the function that generates the predicted marginal effects.
marginal.effect.plot<-function(party="Democrat"){
  seq.number<-0.1
  value<-seq(0,1, seq.number)
  if(party=="Democrat"){
    enth.in<-pred.generator(m2, "in.party.enthusiasm", 0)[[1]]
    enth.out<-pred.generator(m2, "out.party.enthusiasm", 0)[[1]]
    anx.in<-pred.generator(m2, "in.party.anxiety", 0)[[1]]
    anx.out<-pred.generator(m2, "out.party.anxiety", 0)[[1]]
    
    for(i in 2:length(value)){
      enth.in[i,]<-rbind(pred.generator(m2, "in.party.enthusiasm", value[i])[[1]])
      enth.out[i,]<-rbind(pred.generator(m2, "out.party.enthusiasm", value[i])[[1]])
      anx.in[i,]<-rbind(pred.generator(m2, "in.party.anxiety", value[i])[[1]])
      anx.out[i,]<-rbind(pred.generator(m2, "out.party.anxiety", value[i])[[1]])
    }
    
    enth.in$emotion<-seq(0, 1, seq.number)
    enth.in$type<-"In Party Enthusiasm"
    enth.out$emotion<-seq(0, 1, seq.number)
    enth.out$type<-"Out Party Enthusiasm"
    anx.in$emotion<-seq(0, 1, seq.number)
    anx.in$type<-"In Party Anxiety"
    anx.out$emotion<-seq(0, 1, seq.number)
    anx.out$type<-"Out Party Anxiety"
  }
  
  if(party=="Independent"){
    enth.in<-pred.generator(m2, "in.party.enthusiasm", value=0)[[2]]
    enth.out<-pred.generator(m2, "out.party.enthusiasm", 0)[[2]]
    anx.in<-pred.generator(m2, "in.party.anxiety", 0)[[2]]
    anx.out<-pred.generator(m2, "out.party.anxiety", 0)[[2]]
    
    for(i in 2:length(value)){
      enth.in[i,]<-rbind(pred.generator(m2, "in.party.enthusiasm", value[i])[[2]])
      enth.out[i,]<-rbind(pred.generator(m2, "out.party.enthusiasm", value[i])[[2]])
      anx.in[i,]<-rbind(pred.generator(m2, "in.party.anxiety", value[i])[[2]])
      anx.out[i,]<-rbind(pred.generator(m2, "out.party.anxiety", value[i])[[2]])
    }
    
    enth.in$emotion<-seq(0, 1, seq.number)
    enth.in$type<-"In Party Enthusiasm"
    enth.out$emotion<-seq(0, 1, seq.number)
    enth.out$type<-"Out Party Enthusiasm"
    anx.in$emotion<-seq(0, 1, seq.number)
    anx.in$type<-"In Party Anxiety"
    anx.out$emotion<-seq(0, 1, seq.number)
    anx.out$type<-"Out Party Anxiety"
  }
  
  if(party=="Republican"){
    enth.in<-pred.generator(m2, "in.party.enthusiasm", 0)[[3]]
    enth.out<-pred.generator(m2, "out.party.enthusiasm", 0)[[3]]
    anx.in<-pred.generator(m2, "in.party.anxiety", 0)[[3]]
    anx.out<-pred.generator(m2, "out.party.anxiety", 0)[[3]]
    
    for(i in 2:length(value)){
      enth.in[i,]<-rbind(pred.generator(m2, "in.party.enthusiasm", value[i])[[3]])
      enth.out[i,]<-rbind(pred.generator(m2, "out.party.enthusiasm", value[i])[[3]])
      anx.in[i,]<-rbind(pred.generator(m2, "in.party.anxiety", value[i])[[3]])
      anx.out[i,]<-rbind(pred.generator(m2, "out.party.anxiety", value[i])[[3]])
    }
    
    enth.in$emotion<-seq(0, 1, seq.number)
    enth.in$type<-"In Party Enthusiasm"
    enth.out$emotion<-seq(0, 1, seq.number)
    enth.out$type<-"Out Party Enthusiasm"
    anx.in$emotion<-seq(0, 1, seq.number)
    anx.in$type<-"In Party Anxiety"
    anx.out$emotion<-seq(0, 1, seq.number)
    anx.out$type<-"Out Party Anxiety"
  }
  return(rbind(enth.in, enth.out, anx.in, anx.out))
}
plot.data.democrat<-marginal.effect.plot("Democrat")
plot.data.republican<-marginal.effect.plot("Republican")
plot.data.independent<-marginal.effect.plot("Independent")

in.party.enthusiasm<-rbind(subset(plot.data.democrat, type=="In Party Enthusiasm"),
                           subset(plot.data.republican, type=="In Party Enthusiasm"),
                           subset(plot.data.independent, type=="In Party Enthusiasm")
)
in.party.enthusiasm$Party<-rep(c("Democrat", "Republican", "Independent"), each=11)

out.party.enthusiasm<-rbind(subset(plot.data.democrat, type=="Out Party Enthusiasm"),
                            subset(plot.data.republican, type=="Out Party Enthusiasm"),
                            subset(plot.data.independent, type=="Out Party Enthusiasm")
)

out.party.enthusiasm$Party<-rep(c("Democrat", "Republican", "Independent"), each=11)

in.party.anxiety<-rbind(subset(plot.data.democrat, type=="In Party Anxiety"),
                        subset(plot.data.republican, type=="In Party Anxiety"),
                        subset(plot.data.independent, type=="In Party Anxiety")
)
in.party.anxiety$Party<-rep(c("Democrat", "Republican", "Independent"), each=11)

out.party.anxiety<-rbind(subset(plot.data.democrat, type=="Out Party Anxiety"),
                         subset(plot.data.republican, type=="Out Party Anxiety"),
                         subset(plot.data.independent, type=="Out Party Anxiety")
)
out.party.anxiety$Party<-rep(c("Democrat", "Republican", "Independent"), each=11)


### Generate the Figure 
names(in.party.enthusiasm)<-c("min1", "min2", "max2", "max1", "mean", "emotion", "type", "Party")
names(out.party.anxiety)<-c("min1", "min2", "max2", "max1", "mean", "emotion", "type", "Party")
names(in.party.anxiety)<-c("min1", "min2", "max2", "max1", "mean", "emotion", "type", "Party")
names(out.party.enthusiasm)<-c("min1", "min2", "max2", "max1", "mean", "emotion", "type", "Party")
plot.figure<-rbind(out.party.anxiety, out.party.enthusiasm, in.party.anxiety, in.party.enthusiasm)
plot.figure$Affect<-rep(c("Consistent (Negative)", "Inconsistent (Positive)", "Inconsistent (Negative)", "Consistent (Positive)"), each=nrow(out.party.enthusiasm))

plot1<-
    ggplot(plot.figure) + 
    facet_wrap(~Affect)+
    geom_ribbon(aes(x=emotion, ymin=min1, ymax=max1, group=Party), fill="lightgrey", alpha=0.5)+
    geom_ribbon(aes(x=emotion, ymin=min2, ymax=max2, group=Party), fill="lightgrey", alpha=0.75)+
    geom_line(aes(x=emotion, y=mean, colour=Party))+
    scale_colour_manual(name="Party", values=c("black", "grey50", "grey79"))+
    theme_bw() +
    #  theme(legend.position="none") +
    # Format the grid
    theme(panel.grid.major=element_line(colour="#D0D0D0",size=.25)) +
    theme(axis.ticks=element_blank())+
    ggtitle("Affective Consistency and Party Identification") +
    theme(panel.background=element_rect(fill="white")) +
    theme(plot.background=element_rect(fill="white")) +
    theme(panel.border=element_rect(colour="white")) +
    theme(plot.title=element_text(face="bold",hjust=-.08,vjust=2,colour="#3C3C3C",size=11)) +
    theme(axis.text.x=element_text(size=9,colour="#535353",face="bold")) +
    theme(axis.text.y=element_text(size=9,colour="#535353",face="bold")) +
    theme(axis.title.y=element_text(size=9,colour="#535353",face="bold",vjust=1.5)) +
    theme(axis.title.x=element_text(size=9,colour="#535353",face="bold",vjust=-.5)) +
    scale_y_continuous("Marginal Effect of Ideology", limits=c(-1,1))+
    scale_x_continuous("Emotion")+
    geom_hline(yintercept=0)
  
####################################################################################  
pdf("/users/chrisweber/Dropbox/Working Projects/Nick Davis_Polarization Emotion/paper/Figure2.pdf", width=8, height=7)
plot1
dev.off()
####################################################################################


####################################################################################
#################################################################################
##################################################  ##########################################
##### Marginal Effects for Consistency######
##################################################  ##########################################
####################################################################################
# PID/ Table 1/ Figure 2
## Table ###

d1$policy.conservatism<-zero.one(d1$policy.conservatism)
d1$intAnxIn3<-d1$policy.conservatism*d1$anxiety.in
d1$intAnxOut3<-d1$policy.conservatism*d1$anxiety.out
d1$intEnthIn3<-d1$policy.conservatism*d1$enthusiasm.in
d1$intEnthOut3<-d1$policy.conservatism*d1$enthusiasm.out

m1<-glm(consistency.score~
          ideology3+anxiety.in+anxiety.out+enthusiasm.in+enthusiasm.out+
          catholic+no.religion+other.religion+racial.resentment+
          female+education+news+non.white+
          age+year2012+year2016
        , data=d1, family=binomial)  ### Generate image here. 


m2<-polr(as.factor(ideology3)~policy.conservatism+anxiety.in+anxiety.out+enthusiasm.in+enthusiasm.out+intAnxIn3+
           intAnxOut3+intEnthIn3+intEnthOut3+
           catholic+no.religion+other.religion+racial.resentment+
           female+education+news+non.white+
           age+year2012+year2016, data=d1) ## Same here ##

anx.in<-predicted.value.logit(m1, 0, emotion="anxiety.in", model="logit")
anx.out<-predicted.value.logit(m1, 0, emotion="anxiety.out", model="logit")
enth.in<-predicted.value.logit(m1, 0, emotion="enthusiasm.in", model="logit")
enth.out<-predicted.value.logit(m1, 0, emotion="enthusiasm.out", model="logit")

value<-seq(0,1, 0.1)
for(i in 2:length(value)){
  enth.in[i,]<-rbind(predicted.value.logit(m1, value[i], emotion="enthusiasm.in", model="logit"))
  enth.out[i,]<-rbind(predicted.value.logit(m1, value[i],emotion="enthusiasm.out",  model="logit"))
  anx.in[i,]<-rbind(predicted.value.logit(m1, value[i],emotion="anxiety.in", model="logit"))
  anx.out[i,]<-rbind(predicted.value.logit(m1,value[i], emotion="anxiety.out",  model="logit"))
}    

names(enth.in)<-c("min1", "min2", "max2", "max1", "mean")
names(enth.out)<-c("min1", "min2", "max2", "max1", "mean")
names(anx.in)<-c("min1", "min2", "max2", "max1", "mean")
names(anx.out)<-c("min1", "min2", "max2", "max1", "mean")
enth.in$emotion<-value
enth.out$emotion<-value
anx.in$emotion<-value
anx.out$emotion<-value
plot.figure<-rbind(anx.out, enth.out, anx.in, enth.in)
plot.figure$Affect<-rep(c("Consistent (Negative)", "Inconsistent (Positive)", "Inconsistent (Negative)", "Consistent (Positive)"), each=nrow(enth.in))

plot1<-
  ggplot(plot.figure) + 
  facet_wrap(~Affect)+
  geom_ribbon(aes(x=emotion, ymin=min1, ymax=max1), fill="lightgrey", alpha=0.5)+
  geom_ribbon(aes(x=emotion, ymin=min2, ymax=max2), fill="lightgrey", alpha=0.75)+
  geom_line(aes(x=emotion, y=mean))+
  theme_bw() +
  #  theme(legend.position="none") +
  # Format the grid
  theme(panel.grid.major=element_line(colour="#D0D0D0",size=.25)) +
  theme(axis.ticks=element_blank())+
  ggtitle("Affective Consistency and Policy Consistency") +
  theme(panel.background=element_rect(fill="white")) +
  theme(plot.background=element_rect(fill="white")) +
  theme(panel.border=element_rect(colour="white")) +
  theme(plot.title=element_text(face="bold",hjust=-.08,vjust=2,colour="#3C3C3C",size=11)) +
  theme(axis.text.x=element_text(size=9,colour="#535353",face="bold")) +
  theme(axis.text.y=element_text(size=9,colour="#535353",face="bold")) +
  theme(axis.title.y=element_text(size=9,colour="#535353",face="bold",vjust=1.5)) +
  theme(axis.title.x=element_text(size=9,colour="#535353",face="bold",vjust=-.5)) +
  scale_y_continuous("Predicted Probability", limits=c(0,0.4))+
  scale_x_continuous("Emotion")+
  geom_hline(yintercept=0)

####################################################################################  
pdf("/users/chrisweber/Dropbox/Working Projects/Nick Davis_Polarization Emotion/paper/Figure3.pdf", width=8, height=7)
plot1
dev.off()
####################################################################################


marginal.effect.ideology<-function(party="Liberal"){
    seq.number<-0.1
    value<-seq(0,1, seq.number)
    if(party=="Liberal"){
      enth.in<-pred.generator(m2, "in.party.enthusiasm", 0)[[1]]
      enth.out<-pred.generator(m2, "out.party.enthusiasm", 0)[[1]]
      anx.in<-pred.generator(m2, "in.party.anxiety", 0)[[1]]
      anx.out<-pred.generator(m2, "out.party.anxiety", 0)[[1]]
      
      for(i in 2:length(value)){
        enth.in[i,]<-rbind(pred.generator(m2, "in.party.enthusiasm", value[i])[[1]])
        enth.out[i,]<-rbind(pred.generator(m2, "out.party.enthusiasm", value[i])[[1]])
        anx.in[i,]<-rbind(pred.generator(m2, "in.party.anxiety", value[i])[[1]])
        anx.out[i,]<-rbind(pred.generator(m2, "out.party.anxiety", value[i])[[1]])
      }
      
      enth.in$emotion<-seq(0, 1, seq.number)
      enth.in$type<-"In Party Enthusiasm"
      enth.out$emotion<-seq(0, 1, seq.number)
      enth.out$type<-"Out Party Enthusiasm"
      anx.in$emotion<-seq(0, 1, seq.number)
      anx.in$type<-"In Party Anxiety"
      anx.out$emotion<-seq(0, 1, seq.number)
      anx.out$type<-"Out Party Anxiety"
    }
    
    if(party=="Moderate"){
      enth.in<-pred.generator(m2, "in.party.enthusiasm", 0)[[2]]
      enth.out<-pred.generator(m2, "out.party.enthusiasm", 0)[[2]]
      anx.in<-pred.generator(m2, "in.party.anxiety", 0)[[2]]
      anx.out<-pred.generator(m2, "out.party.anxiety", 0)[[2]]
      
      for(i in 2:length(value)){
        enth.in[i,]<-rbind(pred.generator(m2, "in.party.enthusiasm", value[i])[[2]])
        enth.out[i,]<-rbind(pred.generator(m2, "out.party.enthusiasm", value[i])[[2]])
        anx.in[i,]<-rbind(pred.generator(m2, "in.party.anxiety", value[i])[[2]])
        anx.out[i,]<-rbind(pred.generator(m2, "out.party.anxiety", value[i])[[2]])
      }
      
      enth.in$emotion<-seq(0, 1, seq.number)
      enth.in$type<-"In Party Enthusiasm"
      enth.out$emotion<-seq(0, 1, seq.number)
      enth.out$type<-"Out Party Enthusiasm"
      anx.in$emotion<-seq(0, 1, seq.number)
      anx.in$type<-"In Party Anxiety"
      anx.out$emotion<-seq(0, 1, seq.number)
      anx.out$type<-"Out Party Anxiety"
    }
    
    if(party=="Conservative"){
      enth.in<-pred.generator(m2, "in.party.enthusiasm", 0)[[3]]
      enth.out<-pred.generator(m2, "out.party.enthusiasm", 0)[[3]]
      anx.in<-pred.generator(m2, "in.party.anxiety", 0)[[3]]
      anx.out<-pred.generator(m2, "out.party.anxiety", 0)[[3]]
      
      for(i in 2:length(value)){
        enth.in[i,]<-rbind(pred.generator(m2, "in.party.enthusiasm", value[i])[[3]])
        enth.out[i,]<-rbind(pred.generator(m2, "out.party.enthusiasm", value[i])[[3]])
        anx.in[i,]<-rbind(pred.generator(m2, "in.party.anxiety", value[i])[[3]])
        anx.out[i,]<-rbind(pred.generator(m2, "out.party.anxiety", value[i])[[3]])
      }
      
      enth.in$emotion<-seq(0, 1, seq.number)
      enth.in$type<-"In Party Enthusiasm"
      enth.out$emotion<-seq(0, 1, seq.number)
      enth.out$type<-"Out Party Enthusiasm"
      anx.in$emotion<-seq(0, 1, seq.number)
      anx.in$type<-"In Party Anxiety"
      anx.out$emotion<-seq(0, 1, seq.number)
      anx.out$type<-"Out Party Anxiety"
    }
    return(rbind(enth.in, enth.out, anx.in, anx.out))
}



  plot.data.liberal<-marginal.effect.ideology("Liberal")
  plot.data.conservative<-marginal.effect.ideology("Conservative")
  plot.data.moderate<-marginal.effect.ideology("Moderate")
  
  in.party.enthusiasm<-rbind(subset(plot.data.liberal, type=="In Party Enthusiasm"),
                             subset(plot.data.moderate, type=="In Party Enthusiasm"),
                             subset(plot.data.conservative, type=="In Party Enthusiasm")
  )
  in.party.enthusiasm$Party<-rep(c("Liberal", "Moderate", "Conservative"), each=11)
  
  out.party.enthusiasm<-rbind(subset(plot.data.liberal, type=="Out Party Enthusiasm"),
                              subset(plot.data.moderate, type=="Out Party Enthusiasm"),
                              subset(plot.data.conservative, type=="Out Party Enthusiasm")
  )
  
  out.party.enthusiasm$Party<-rep(c("Liberal", "Moderate", "Conservative"), each=11)
  
  in.party.anxiety<-rbind(subset(plot.data.liberal, type=="In Party Anxiety"),
                          subset(plot.data.moderate, type=="In Party Anxiety"),
                          subset(plot.data.conservative, type=="In Party Anxiety")
  )
  in.party.anxiety$Party<-rep(c("Liberal", "Moderate", "Conservative"), each=11)
  
  out.party.anxiety<-rbind(subset(plot.data.liberal, type=="Out Party Anxiety"),
                           subset(plot.data.moderate, type=="Out Party Anxiety"),
                           subset(plot.data.conservative, type=="Out Party Anxiety")
  )
  out.party.anxiety$Party<-rep(c("Liberal", "Moderate", "Conservative"), each=11)
  
  ### Generate the Figure 
  names(in.party.enthusiasm)<-c("min1", "min2", "max2", "max1", "mean", "emotion", "type", "Party")
  names(out.party.anxiety)<-c("min1", "min2", "max2", "max1", "mean", "emotion", "type", "Party")
  names(in.party.anxiety)<-c("min1", "min2", "max2", "max1", "mean", "emotion", "type", "Party")
  names(out.party.enthusiasm)<-c("min1", "min2", "max2", "max1", "mean", "emotion", "type", "Party")
  
  plot.figure<-rbind(out.party.anxiety, out.party.enthusiasm, in.party.anxiety, in.party.enthusiasm)
  plot.figure$Affect<-rep(c("Consistent (Negative)", "Inconsistent (Positive)", "Inconsistent (Negative)", "Consistent (Positive)"), each=nrow(out.party.enthusiasm))
  
  
  plot1<-
    ggplot(plot.figure) + 
    facet_wrap(~Affect)+
    geom_ribbon(aes(x=emotion, ymin=min1, ymax=max1, group=Party), fill="lightgrey", alpha=0.5)+
    geom_ribbon(aes(x=emotion, ymin=min2, ymax=max2, group=Party), fill="lightgrey", alpha=0.75)+
    geom_line(aes(x=emotion, y=mean, colour=Party))+
    scale_colour_manual(name="Party", values=c("black", "grey50", "grey79"))+
    theme_bw() +
    #  theme(legend.position="none") +
    # Format the grid
    theme(panel.grid.major=element_line(colour="#D0D0D0",size=.25)) +
    theme(axis.ticks=element_blank())+
    ggtitle("Affective Consistency, Symbolic Ideology, and Operational Ideology") +
    theme(panel.background=element_rect(fill="white")) +
    theme(plot.background=element_rect(fill="white")) +
    theme(panel.border=element_rect(colour="white")) +
    theme(plot.title=element_text(face="bold",hjust=-.08,vjust=2,colour="#3C3C3C",size=11)) +
    theme(axis.text.x=element_text(size=9,colour="#535353",face="bold")) +
    theme(axis.text.y=element_text(size=9,colour="#535353",face="bold")) +
    theme(axis.title.y=element_text(size=9,colour="#535353",face="bold",vjust=1.5)) +
    theme(axis.title.x=element_text(size=9,colour="#535353",face="bold",vjust=-.5)) +
    scale_y_continuous("Marginal Effect of Operational Ideology", limits=c(-1,1))+
    scale_x_continuous("Emotion")+
    geom_hline(yintercept=0)
  
  ####################################################################################  
  pdf("/users/chrisweber/Dropbox/Working Projects/Nick Davis_Polarization Emotion/paper/Figure4.pdf", width=8, height=7)
  plot1
  dev.off()
  ####################################################################################

  ## Table ###
  out1<-rbind(coef(summary(m1)) [c(2:6),1:2], c(NA,NA), c(NA,NA), c(NA,NA), c(NA,NA)) #ANES


  out2<-rbind(coef(summary(m2)) [c(2:10),1:2]) #ANES
  results1<-as.matrix(
    cbind(out1, out2
    ))

  row.names(results1)<-c("Operational Ideology", "In Party Negative", "Out Party Negative", "In Party Positive", "Out Party Positive", "Out Party Negative x Ideology", "In Party Negative x Ideology", "Out Party Positive x Ideology", "In Party Positive x Ideology")
  require(xtable)
  xtable(coef(summary(m1))[,1:2], digits=3)
  xtable(coef(summary(m2))[,1:2], digits=3)
  
  